package com.iweb.oasys.dao;

import com.iweb.oasys.component.JdbcTemplate;
import com.iweb.oasys.entity.Menu;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MeunDaoImpl implements MenuDao{
    private static MenuDao menuDao = new MeunDaoImpl();
    private MeunDaoImpl() {}
    public static  MenuDao getInstance() {
        return menuDao;
    }
    @Override
    public List<Menu> queryMenuList() throws SQLException {
        /* 主动过滤掉 is_show=0 的菜单 */
        String sql = "select * from menu where menu_sort is not null and is_show=1 order by menu_sort ";
        ResultSet resultSet = JdbcTemplate.query(sql);
        List<Menu> menuList = new ArrayList<>();
        while (resultSet.next()) {
            Menu menu = new Menu();
            menu.setMenuId(resultSet.getInt("menu_id"));
            menu.setMenuName(resultSet.getString("menu_name"));
            menu.setMenuUrl(resultSet.getString("menu_url"));
            menu.setMenuIcon(resultSet.getNString("menu_icon"));
            menu.setMenuSort(resultSet.getInt("menu_sort"));
            menu.setParentId(resultSet.getInt("parent_id"));
            menu.setIsShow(resultSet.getInt("is_show"));
            /* 把menu对象存储到集合中 */
            menuList.add(menu);
            sql = "select * from menu where parent_id=? and is_show=1";
            ResultSet resultSet1 = JdbcTemplate.query(sql, menu.getMenuId());
            while (resultSet1.next()) {
                Menu submenu = new Menu();
                submenu.setMenuId(resultSet1.getInt("menu_id"));
                submenu.setMenuName(resultSet1.getString("menu_name"));
                submenu.setMenuUrl(resultSet1.getString("menu_url"));
                submenu.setMenuIcon(resultSet1.getNString("menu_icon"));
                submenu.setMenuSort(resultSet1.getInt("menu_sort"));
                submenu.setParentId(resultSet1.getInt("parent_id"));
                submenu.setIsShow(resultSet1.getInt("is_show"));
                /* 把menu对象存储到集合中 */
                menuList.add(submenu);
            }
        }
        /* 返回菜单集合 */
        return menuList;
    }
    @Override
    public int queryVersion() throws SQLException {
        String sql = "select version from version where name='menu'";
        ResultSet resultSet = JdbcTemplate.query(sql);
        int version = -1;
        if(resultSet.next())
        {
            version = resultSet.getInt("version");
        }
        return version;
    }
}
